package com.wei.duowan.bbs.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;

/**
 * 作者：赵若位
 * 时间：2019/10/20 20:42
 * 联系方式：1070138445
 * 功能：
 */
public class ForumsFloatingImageBehavior extends CoordinatorLayout.Behavior<LinearLayout>
{

    private static final String TAG = ForumsFloatingImageBehavior.class.getSimpleName();
    private static final long DURATION = 200;


    public ForumsFloatingImageBehavior()
    {
    }

    public ForumsFloatingImageBehavior(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull LinearLayout child, @NonNull View dependency)
    {
        return dependency instanceof ViewPager;
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull LinearLayout child, @NonNull View directTargetChild, @NonNull View target, int axes, int type)
    {
        return true;
    }


    @Override
    public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull LinearLayout child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type)
    {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
        Log.e(TAG, "onNestedScroll: " + dyConsumed);
        if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE)
        {
            hide(child);
            return;
        }

        if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE)
        {
            show(child);
            return;
        }
    }


    private void hide(@Nullable View view)
    {
        Log.e(TAG, "hide: ");
        view.setVisibility(View.INVISIBLE);
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f
        );
        animation.setDuration(DURATION);
        view.setAnimation(animation);
    }


    public void show(@Nullable View view)
    {
        Log.e(TAG, "show: ");
        view.setVisibility(View.VISIBLE);
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_PARENT, 0.0f
        );
        animation.setDuration(DURATION);
        view.setAnimation(animation);
    }
}
